#include "bsp_ads1110.h"

#include "systick.h"

#define ADS1110_WADDR 0x90
#define ADS1110_RADDR 0x91

#define ADS_1_WR(w,x,y)  dv_I2C.fadsWrite(mI2_ads1,w,x,y)
#define ADS_1_RD(w,x,y)  dv_I2C.fadsRead(mI2_ads1,w,x,y)

#define ADS_2_WR(w,x,y)  dv_I2C.fadsWrite(mI2_ads2,w,x,y)
#define ADS_2_RD(w,x,y)  dv_I2C.fadsRead(mI2_ads2,w,x,y)

#define ADS_3_WR(w,x,y)  dv_I2C.fadsWrite(mI2_ads3,w,x,y)
#define ADS_3_RD(w,x,y)  dv_I2C.fadsRead(mI2_ads3,w,x,y)

#define ADS_4_WR(w,x,y)  dv_I2C.fadsWrite(mI2_ads4,w,x,y)
#define ADS_4_RD(w,x,y)  dv_I2C.fadsRead(mI2_ads4,w,x,y)

dv_ADS_TypeDef dv_ADS;


static int16_t bsp_ads1110_Read(EM_ADS_CH_t chl)
{
    uint8_t databuff[3] ={0};
    union 
    {
        uint16_t val;
        uint8_t data[2];        
    }u16temp;
    
    int16_t vol = 0;

    switch (chl)
    {
        case EM_ADS_CH1:
            ADS_1_RD(ADS1110_RADDR,databuff,3);
            u16temp.data[0] = databuff[1];
            u16temp.data[1] = databuff[0];        
            break;
        case EM_ADS_CH2:
            ADS_2_RD(ADS1110_RADDR,databuff,3);
            u16temp.data[0] = databuff[1];
            u16temp.data[1] = databuff[0]; 
            break;
        case EM_ADS_CH3:
            ADS_3_RD(ADS1110_RADDR,databuff,3);
            u16temp.data[0] = databuff[1];
            u16temp.data[1] = databuff[0]; 
            break;
        case EM_ADS_CH4:
            ADS_4_RD(ADS1110_RADDR,databuff,3);
            u16temp.data[0] = databuff[1];
            u16temp.data[1] = databuff[0]; 
            break;        
        default:
            u16temp.data[0] = 0;
            u16temp.data[1] = 0; 
            break;
    }

    if(u16temp.val>=0x8000)
    {
        u16temp.val = 0xFFFF - u16temp.val + 1;
        vol = -(float)(u16temp.val*2048/0x8000);
    }
    else
    {
        vol = (float)(u16temp.val*2048/0x7FFF);
    }
    
    return vol;
}

static void bsp_ads1110_Init()
{
    uint8_t data = 0x8C;
    ADS_1_WR(ADS1110_WADDR,&data,1);
    ADS_2_WR(ADS1110_WADDR,&data,1);
    ADS_3_WR(ADS1110_WADDR,&data,1);
    ADS_4_WR(ADS1110_WADDR,&data,1);
}

void init_bsp_ads(void)
{
    dv_ADS.finit = bsp_ads1110_Init;
    dv_ADS.fread = bsp_ads1110_Read;
}